import { useRouter } from 'next/router';
import { connect } from 'react-redux';
import { useState } from 'react';
import { message } from 'antd';
import Cookies from 'js-cookie';
import { validatePhoneNo, validateIDCard, loopEvetyIdCard } from '@/utils';
// 组件
import PayModal from '@/pages_components/pay/PayModal';
import Spin from '@/components/Spin';
// css
import styles from '@/styles/CommonOrder.module.scss';
// api
import { createOrder, orderPayH5 } from '@/api/order';

const OrderPay = ({ order: { price, amount, stock }, data: { target, realName, buyLimit } }) => {
    
    const router = useRouter();
    const isHotel = target === '/hotel',
         { orderNumberType } = buyLimit || {};

    const [loading, setLoading] = useState(false);
    const [visible, setVisible] = useState(false);
    const [orderId, setOrderId] = useState('');
    const [codeUrl, setCodeUrl] = useState('');

    const defaultParams = {
        // 暂时没用的字段
        channelId: 1,
        channelName: "",
        companyId: "",
        certificateType: "1",
        distributorPhone: "",
        managerId: 0,
        managerName: "",
        memberId: 0,
        orderFrom: 2,
        orderSource: 5,
        threeOrderNo: "",
        ticketNo: "",
        ticketSystemCode: "",
        contactDTOS: {},
        extObject: {},
        // 优惠券相关
        activityBaseId: "",
        activityRuleId: "",
        algorithms: "",
        couponId: "",
        saleType: 0,
        // 需要更新的字段
        certificateNo: "",
        customerName: "",
        phone: "",
        extraInformation: {},
        goodsInfoParamList: [], // { amount: 0, customerId: 0, saleId: 0, skuId: 0, }
    }

    // 提交订单
    function confirmOrder() {
        const coupon = JSON.parse(Cookies.get('order_coupon') || '{}');
        const params = {
            ...defaultParams,
            customerName: Cookies.get('order_contact'),
            phone: Cookies.get('order_phone'),
            certificateNo: Cookies.get('order_idcard') || "",
        }

        // 选择优惠券
        if(Object.keys(coupon).length){
            let { couponId, activityBaseId, activityRuleId, algorithms, saleRole, minusRule, reservationRole } = coupon;
            if(saleRole){
                params.saleType = saleRole.saleType;
            }else if(minusRule){
                params.saleType = minusRule.minusRuleAlgorithmList[0].saleType;
            }else if(reservationRole){
                params.saleType = reservationRole[0].saleType;
            }
            params.couponId = couponId || "";
            params.activityBaseId = activityBaseId || "";
            params.activityRuleId = activityRuleId || "";
            params.algorithms = algorithms || "";
        }

        const _amount = Cookies.get('order_number'),
            _skuId = Cookies.get('order_goodsExtendId'),
            _customers = JSON.parse(Cookies.get('order_select_customers') || "[]"),
            _selectCustomers = _customers.filter(item => item.checked) || [];
        // 线路
        if (target === '/line') {
            params.userRemark = Cookies.get('order_remark') || "";
        }
        // 非酒店
        if (target !== '/hotel') {
            params.extraInformation['useDate'] = Cookies.get('order_select_date');
        } else {
            // 酒店
            params.extraInformation['useDate'] = Cookies.get('order_hotel_startDate');
            params.comeDate = Cookies.get('order_hotel_startDate');
            params.leaveDate = Cookies.get('order_hotel_endDate');
            params.homeNum = _amount;
        }
        // 实名制
        if (realName > 1) {
            if(!_selectCustomers.length) {
                message.warning('请选择出行游客');
                return
            }
            // 判断数量，和游客数是否相同，否则无法提交
            if(realName === 3 && orderNumberType == 2 && _amount !== _selectCustomers.length){
                message.warning(`出行人数必须等于所填写的${isHotel?'房间':''}数量`);
                return
            }
            params.goodsInfoParamList = [];
            _selectCustomers.forEach(item => {
                params.goodsInfoParamList.push({
                    skuId: _skuId,
                    amount: realName === 3 ? 1 : _amount,
                    customerId: item.id,
                    saleId: 0,
                })
            })
        } else { // 无需实名
            params.goodsInfoParamList = [
                {
                    skuId: _skuId,
                    amount: _amount,
                    customerId: 0,
                    saleId: 0,
                }
            ]
        }
        // 判断联系人/手机号
        if (!params.customerName || !params.phone) {
            message.warning('请填写联系人/手机号');
            return
        }
        if (!validatePhoneNo(params.phone)) {
            message.warning('手机号格式错误');
            return
        }
        // 酒店需要判断身份证号
        if(isHotel){
            const { status, msg } = validateIDCard(params.certificateNo);
            if(status < 1){
                message.warning(msg);
                return
            }
        }
        // 判断购买限制（儿童、成人、老年票/性别等）
        const result = loopEvetyIdCard(realName, _selectCustomers);
        if(!result){
          return false
        }

        // console.log(params);return
        setLoading(true);
        
        // 创建订单
        createOrder(target, params).then(res => {
            const { code, data: orderId } = res;
            if (code == 0) {
                // 微信支付
                orderPayH5(orderId).then(result => {
                    let { data } = result;
                    if(data.code_url){
                        setOrderId(orderId);
                        setCodeUrl(data.code_url);
                        setVisible(true);
                    }else{
                        message.error('发送请求失败，请重试');
                    }
                })
            }
            if(code == 1290){
                message.success('支付成功');
                router.push(`/pay_success?redirect=/`);
            }
            setLoading(false);
        })
    }

    return (
        <>
            <Spin loading={loading} />
            <div className={styles['product-order']}>
                <button disabled={!stock} onClick={() => { confirmOrder() }}>{stock?'提交订单':'暂无库存'}</button>
                <span className={styles['amount']}>（数量：{amount}）</span>
                <span className={styles['price']}><em>￥</em><b>{price}</b></span>
                <span className={styles['title']}>实际支付</span>
            </div>
            <PayModal target={target} visible={visible} setVisible={setVisible} orderId={orderId} codeUrl={codeUrl} />
        </>
    )
}
const mapStateToProps = (state) => {
    return {
        order: state.order
    }
}
export default connect(mapStateToProps, null)(OrderPay)